package xyz.ssf.cloud.common.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import xyz.ssf.cloud.common.interceptor.JwtAuthInterceptor;
import org.springframework.util.StringUtils;

import lombok.RequiredArgsConstructor;

/**
 * Web MVC配置
 * 
 * @author ssf
 */
@Configuration
@RequiredArgsConstructor
public class WebMvcConfig implements WebMvcConfigurer {
    
    @Autowired
    private JwtAuthInterceptor jwtAuthInterceptor;
    
    private final StorageConfig storageConfig;
    
    /**
     * 添加拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 添加JWT认证拦截器
        registry.addInterceptor(jwtAuthInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/auth/login", "/auth/captcha", "/user/login", "/user/captcha");
    }
    
    /**
     * 跨域配置
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600);
    }
    
    /**
     * 配置静态资源映射
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 配置本地文件上传路径映射
        StorageConfig.Local local = storageConfig.getLocal();
        String storagePath = local.getStoragePath();
        String accessPath = local.getAccessPath();
        
        if (!StringUtils.hasText(storagePath)) {
            storagePath = "upload";
        }
        
        if (!StringUtils.hasText(accessPath)) {
            accessPath = "/upload";
        }
        
        // 确保路径格式正确
        if (!accessPath.startsWith("/")) {
            accessPath = "/" + accessPath;
        }
        
        if (!accessPath.endsWith("/")) {
            accessPath = accessPath + "/";
        }
        
        // 添加资源映射
        registry.addResourceHandler(accessPath + "**")
                .addResourceLocations("file:" + storagePath + "/");
    }
}